package pb032.droid.nav;

/**
 * Orientated by http://marakana.com/forums/android/examples/40.html
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import xor.droid.nav.R;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.widget.Toast;

public class WiFiScanReceiver extends BroadcastReceiver {

    private IndoorNav indoorNav;

    public WiFiScanReceiver(IndoorNav indoorNav) {
	super();
	this.indoorNav = indoorNav;
    }

    @Override
    public void onReceive(Context c, Intent i) {
	// Result list as Accesspoint objects
	List<AccessPoint> scanResultList = new ArrayList<AccessPoint>();

	// List available AccessPoints as ScanResult objects
	List<ScanResult> scans = indoorNav.getWifi().getScanResults();

	AccessPoint ap;

	// Saving results
	if (scans.isEmpty() == false) {
	    for (ScanResult scan : scans) {
		ap = new AccessPoint(scan.BSSID, scan.SSID, scan.level, scan.frequency);
		scanResultList.add(ap);
	    }
	    // sorting results by Signalstrength
	    Collections.sort(scanResultList);
	    
	    indoorNav.trilaterate(scanResultList);

	    // Output for System checks and calibration
	    indoorNav.updateList(scanResultList);
	    Toast.makeText(indoorNav, "Scan done.", Toast.LENGTH_SHORT).show();
	} else {
	    Toast.makeText(indoorNav, R.string.scanFailedText, Toast.LENGTH_SHORT).show();
	}
    }
}